package cn.dapeng.rpc.server;

import cn.dapeng.rpc.common.codec.MyByteToMessageDecoderV1;
import cn.dapeng.rpc.common.handler.ServerRequestHandlerV1;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class ServerStartupV1 {

    public static void start(int port) {
        NioEventLoopGroup boss = new NioEventLoopGroup(5);

        ServerBootstrap sbs = new ServerBootstrap();
        ChannelFuture bind = sbs.group(boss, boss).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline()
                                .addLast(new MyByteToMessageDecoderV1())
                                .addLast(new ServerRequestHandlerV1());
                    }
                }).bind(port);

        try {
            System.out.println("server startup, port: %s listening ......".formatted(port));
            bind.sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
